<template>
  <div v-if="siteInfo.code === 0" v-cloak id="jianye-container" class="jianye-container" :style="pcStyle">
    <swiper v-if="isSwiper" ref="swiper"></swiper>
    <transition :name="pageTransitionName">
      <pages v-if="!isSwiper"></pages>
    </transition>
    <group-component class="fixed-con" v-if="fixedComps.length > 0" :item="{components: fixedComps}" :pageId="1" :popId="1"></group-component>
    <transition :name="popTransitionName">
      <pops ref="pops"></pops>
    </transition>
    <share v-if="siteAttrs.isShareWeiboWinxin" ref="share" :item="shareItem"></share>
    <van-loading v-if="siteInfo.isInitSite || siteInfo.isLoading || siteInfo.isDisplayAssetsLoading" :size="40" color="#1989fa"></van-loading>
  </div>
  <qrcode v-if="siteInfo.code === 0 && isDisplayQrcode" class="pc-display-qrcode-con"></qrcode>
</template>

<script>
import { wbBase } from '@/components/utils/wbBase'
import { pageLoadAssets } from '@/pages/js/page-load-assets'
import { pageTemplate } from '@/components/utils/page-template'
import { pageAnimate } from '@/others/pages/js/page-animate'
import { useStore } from 'vuex'
import { computed, toRefs, ref, defineAsyncComponent } from 'vue'
import { sendStaticsVisit } from '@/service/site'
import { getPxOVwByValue } from '@/store/utils'
import { EventBus } from '@/store/index'
import { PAGE_TYPE, COMPONENT_TYPES } from '@/common/const'
import { MOBILE_WID_HEI, H5_TYPE } from '@/common/const-dif'
import { getQueryString, isJSON } from '@/plugins/utils'
import { mapGetters, mapState } from 'vuex'
import { EVENT_HOVER_TYPES } from '@/common/events'
import { POP_ANIMATES } from '@/common/const-animates'

const components = {
  GroupComponent: defineAsyncComponent(() => import('@/components/group-component.vue')),
  Pops: defineAsyncComponent(() => import('@/others/pages/pops.vue')),
  Share: defineAsyncComponent(() => import('@/others/pages/share.vue')),
  Pages: defineAsyncComponent(() => import('@/others/pages/pages.vue')),
  Swiper: defineAsyncComponent(() => import('@/others/pages/swiper.vue')),
  Qrcode: defineAsyncComponent(() => import('@/others/pages/qrcode.vue')),
}

export default {
  mixins: [pageTemplate, wbBase, pageLoadAssets, pageAnimate],
  components,
  setup () {
    const store = useStore()
    const siteInfo = computed(() => {
      return store.state.siteInfo
    })
    const siteAttrs = computed(() => {
      return store.state.attrs
    })

    const env_ = import.meta.env
    const env = {
      webUrl: env_.VITE_APP_WEB_URL,
      apiUrl: env_.VITE_APP_API_URL,
    }
    store.commit("setEnvInfo", env)

    let site_id = getQueryString("id")
    let from = getQueryString("from")
    if(from){
      store.commit("setSiteFrom", from)
    }
    let md = new window.MobileDetect(window.navigator.userAgent)
    const isMobile = md.phone()
    store.commit("updateIsMobileInfo", { isMobile, isIPhone: md.is('iPhone'), os: md.os() })

    sendStaticsVisit('visit', site_id)

    if(window.location.href.indexOf("temp") != -1){
       store.dispatch("updateTempSiteData", { id: site_id })
    }else{
      store.dispatch("updateSiteData", { site_id })
    }
    let state = {
      ...toRefs(store.state),
      siteInfo,
      siteAttrs,
      store,
      shareItem: { cid:COMPONENT_TYPES.wb_share, styles:'', btnAttr:{title:''} },
      PAGE_TYPE: PAGE_TYPE,
      loadImgCompId: {},
      gsapStaggers: {},
      gsapPaths: {},
      popTransitionName: ref("fade"),
      pageTransitionName: ref("fade"),
      isNotInterceptPost: true,
      pcQrcodeStyle: {
        width: getPxOVwByValue(400),
        height: getPxOVwByValue(600),
      },
    }
    return state
  },
  created() {
    EventBus.$off("wbsubmit")
    EventBus.$on("wbsubmit", this.onFormSubmit)
    EventBus.$off("login")
    EventBus.$on("login", this.onLoginPopup)
    EventBus.$off("share")
    EventBus.$on("share", this.onSharePopup)
    if(this.siteAttrs.isPopRandomEffect){
      this.popTransitionName = POP_ANIMATES[_.random(0, POP_ANIMATES.length)]
    }
    if(this.siteAttrs.isRandomEffect){
      this.pageTransitionName = POP_ANIMATES[_.random(0, POP_ANIMATES.length)]
    }
  },
  computed: {
    ...mapGetters({
      globalCurrentPage: "getCurrentPage",
      isSwiper: "isSwiper",
    }),
    ...mapState({
      fixedComps: state => state.fixedComps,
    }),
    isDisplayQrcode() {
      let isPC = this.siteAttrs.h5Type == H5_TYPE.pc
      return !this.siteInfo.md.isMobile && !isPC
    },
    pcStyle() {
      let currentPage = this.pages[this.pageIndex];
      let hei = 0;
      if(currentPage) {
        hei = currentPage.styles.height;
      }else{
        let reallyHeight = MOBILE_WID_HEI.clientHeight*MOBILE_WID_HEI.adaptiveScale
        if(MOBILE_WID_HEI.adaptiveScale <= 1 && !this.siteInfo.md.isMobile) {
          reallyHeight = MOBILE_WID_HEI.clientHeight
          if(currentPage && reallyHeight < currentPage.attrs.height) {
            reallyHeight = currentPage.attrs.height
          }
        }
        hei = getPxOVwByValue(parseInt(reallyHeight));
      }
      return {
        width: getPxOVwByValue(parseInt(MOBILE_WID_HEI.clientWidth*MOBILE_WID_HEI.adaptiveScale)),
        height: hei,
        margin: this.siteInfo.md.isMobile ? "0" : "auto",
      }
    },
  },
  methods: {
    onLoginPopup() {
      this.$dialog.confirm({
        title: '',
        message: '亲，确认跳转微博登录页面吗？',
        // theme: 'round-button',
        confirmButtonText: '微博登录',
        confirmButtonColor: '#008000',
        // cancelButtonColor: '#f00'
      })
      .then(() => {
        // on confirm
        window.location.href = "https://passport.weibo.cn/signin/login?entry=mweibo&res=wel&wm=3349&r=" + window.location.href
      })
      .catch(() => {
        // on cancel
        this.$store.commit("updateLoading", { isLoading: false })
      });
      // WeiboJS.invoke("login", { redirect_uri: window.location.href }, function(e){});
      // window.wb.login(window.location.href);
      // if(this.$refs.login) {
      //   this.$refs.login.show();
      // }
    },
    onSharePopup() {
      if(this.$refs.share){
        this.$refs.share.show()
      }
    },
    onFormSubmit({e, item}) {
      const formItemDesc = {
        name: "姓名",
        phone: "手机",
        code: "验证码",
        email: "邮箱",
        telephone: "电话",
        other: "其他",
      }
      let params = {}
      let isSubmit = true
      let msg = ""
      let pageIndex
      let submitContainerId
      let pageId_ = this.globalCurrentPage.id
      let paramStr = item.events.submit.comps[2] && item.events.submit.comps[2].attrs.value;
      let groupCompId = "";
      if(paramStr && isJSON(paramStr)){
        groupCompId = JSON.parse(paramStr).groupCompId;
      }
      //1 多页 2 长页
      if(groupCompId){
        submitContainerId = groupCompId;
      }else if(this.statePopId > 0){
        pageIndex = this.statePopId - 1
        submitContainerId = "pop-" + this.statePopId
      }else{
        if (!this.siteAttrs.isNoSwiping && this.siteAttrs.pageType == PAGE_TYPE.single) {
          if (this.$refs.swiper && this.$refs.swiper.swiper) {
            pageIndex = this.$refs.swiper.swiper.activeIndex;
          }else{
            pageIndex = 0
          }
        } else {
          pageIndex = this.pageIndex
        }
        submitContainerId = "page-" + (pageIndex+1)
      }

      let inputs = document.getElementById(submitContainerId).getElementsByClassName("wb-input");
      for (let i = 0, len = inputs.length; i < len; i++) {
        let input = inputs[i];
        let compId = input.dataset.id;
        let inputData = this.componentMap[compId];
        let key = inputData.commonAttr.name;
        let inputVal = this.formValues[compId] && this.formValues[compId].value;
        let tableName = inputData && inputData.commonAttr.tableName ? inputData.commonAttr.tableName : key + "_" + i
        if (inputData && inputData.commonAttr.need && !inputVal) {
          isSubmit = false
          const hint = formItemDesc[key] ? formItemDesc[key] : tableName;
          msg += hint + "项，不能为空哦！";
          break;
        }
        if(inputData && inputData.commonAttr.rule && inputVal){
          const rule = new RegExp(inputData.commonAttr.rule)
          if(!rule.test(inputVal)){
            isSubmit = false
            const hint = tableName ? tableName : formItemDesc[key];
            msg += hint + "项，格式不正确";
            break;
          }
        }
        if (key == "email" && inputVal.length > 0) {
          // eslint-disable-next-line
          if (/^(\w-*\.*)+@(\w-?)+(\.\w{2,})+$/.test(inputVal)) {
          } else {
            isSubmit = false
            msg += "邮箱格式输入不正确"
            break;
          }
        } else if (key == "phone" || key == "telephone") {
          // eslint-disable-next-line
          if (/^1[0-9]{10}$/.test(inputVal)) {
          } else {
            isSubmit = false
            msg += "电话号码输入不正确"
            break;
          }
        }
        params[tableName] = inputVal;
      }
      //textarea
      let textareas = document.getElementById(submitContainerId).getElementsByClassName("wb-text");
      _.forEach(textareas, (textarea, index) => {
          let compId = textarea.dataset.id;
          let textareaData =  this.componentMap[compId];
          let textareaVal = this.formValues[compId] && this.formValues[compId].value;
        if(textareaData && textareaData.commonAttr.isEdit){
          let tableName;
          if(textareaVal && textareaVal.length > 0){
            tableName = textareaData.commonAttr.tableName ? textareaData.commonAttr.tableName : "textarea_" + index
            params[tableName] = textareaVal;
          }else{
            if(textareaData.commonAttr.need){
              isSubmit = false
              const hint = textareaData.commonAttr.tableName ? textareaData.commonAttr.tableName : "多行文本"
              msg = hint + "项，不能为空哦！"
            }
          }
        }
      })
      //单选
      if (this.isForm.isRadio[pageId_] || groupCompId) {
        //wb-radio
        let wbRadios = document.getElementById(submitContainerId).getElementsByClassName("wb-radio");
        for (let i = 0; i < wbRadios.length; i++) {
          let radioChecked = false
          let compId = wbRadios[i].dataset.id
          let radioValue = ''
          if(this.formValues[compId]){
            radioValue = this.formValues[compId].value
          }
          let radioData =  this.componentMap[compId];
          if(radioValue && radioValue.length > 0){
            let tableName = radioData.commonAttr.tableName ? radioData.commonAttr.tableName : 'radio_' + i
            radioChecked = true;
            params[tableName] = radioValue
          }
          if (!radioChecked && radioData.commonAttr.need) {
            isSubmit = false
            const hint = radioData.commonAttr.tableName ? radioData.commonAttr.tableName + ", " : '单选';
            msg = hint + "没有选哦"
          }
        }
      }
      //多选
      let isCheckboxRelate = false
      if (this.isForm.isCheckbox[pageId_] || groupCompId) {
        //wb-checkbox
        let wbCheckboxs = document.getElementById(submitContainerId).getElementsByClassName("wb-checkbox")
        if(wbCheckboxs && wbCheckboxs.length == 0){
          wbCheckboxs = document.getElementById(submitContainerId).getElementsByClassName("wb-common-list-ul")
          if(wbCheckboxs.length > 0) {
            isCheckboxRelate = true
          }
        }
        for (let i = 0; i < wbCheckboxs.length; i++) {
          let compId = wbCheckboxs[i].dataset.id
          if(!compId){
            break
          }
          let checkboxData = this.componentMap[compId];
          let commonAttr = checkboxData.commonAttr
          let selecteds = []
          let lists = []
          if(this.formValues[compId]){
            selecteds = this.formValues[compId].selecteds
            lists = this.formValues[compId].lists
          }
          let checkboxNum = 0
          let strs = ''
          _.forEach(selecteds, (id) => {
              checkboxNum++
              const str = lists[id-1].title || lists[id-1].text
              strs += str ? str + ',' : id + ','
          })
          if(commonAttr.isOther && this.formValues[compId] && this.formValues[compId].value){
            strs += this.formValues[compId].value
          }
          let max = parseInt(commonAttr.max)
          let min = parseInt(commonAttr.min)
          if (commonAttr.need && min < 1) {
            min = 1
          }
          let tableName = commonAttr.tableName ? commonAttr.tableName : 'checkbox_' + i
          if (checkboxNum >= min && checkboxNum <= max) {
            params[tableName] = strs
          } else {
            isSubmit = false
            const hint = commonAttr.tableName ? commonAttr.tableName + ", " : '';
            msg = hint + "请至少选择" + min + "个选项"
            break
          }
        }
      }
      //下拉菜单
      //wb-dropdown
      if (this.isForm.isDropdown[pageId_] || groupCompId) {
        let dropdownList = document.getElementById(submitContainerId).getElementsByClassName("wb-dropdown");
        _.forEach(dropdownList, (dropdown, index) => {
          let compId = dropdown.dataset.id
          let dropdownValue = ''
          if(this.formValues[compId]){
            dropdownValue = this.formValues[compId].value
          }
          if(dropdownValue.length > 0){
            let dropdownData = this.componentMap[compId];
            let tableName = dropdownData.commonAttr.tableName ? dropdownData.commonAttr.tableName : 'dropdown_' + index
            params[tableName] = dropdownValue
          }
        });
      }

      //地址
      //wb-address
      if (this.isForm.isAddress[pageId_] || groupCompId) {
        let addressList = document.getElementById(submitContainerId).getElementsByClassName("wb-address");
        _.forEach(addressList, (dropdown, index) => {
          let compId = dropdown.dataset.id
          let adressValue = ''
          if(this.formValues[compId]){
            adressValue = this.formValues[compId].value
          }
          if(adressValue.length > 0){
            let dropdownData = this.componentMap[compId];
            let tableName = dropdownData.commonAttr.tableName ? dropdownData.commonAttr.tableName : 'address_' + index
            params[tableName] = adressValue
          }
        });
      }
      // 文件上传
      if (this.isForm.isUpload[pageId_] || groupCompId) {
        let uploadList = document.getElementById(submitContainerId).getElementsByClassName("wb-upload");
        let upload, compId, uploadCompData, tableName_, tableName, uploadUrl, urlLen;
        let uploadUrls = null;
        for(let index = 0, len = uploadList.length; index < len; index++) {
          uploadUrls = null;
          upload = uploadList[index];
          compId = upload.dataset.id;
          uploadCompData = this.componentMap[compId];
          if(this.formValues[compId]) {
            uploadUrls = this.formValues[compId].urls
          };
          if(uploadUrls && uploadUrls.length > 0) {
            urlLen = uploadUrls.length;
            tableName_ = uploadCompData.commonAttr.tableName ? uploadCompData.commonAttr.tableName : '';
            for(let i = 0; i < urlLen; i++) {
              tableName = 'upload' + tableName_ + '_' + index + '_' + i;
              uploadUrl = uploadUrls[i];
              params[tableName] = uploadUrl;
            }
          } else {
            if(uploadCompData.commonAttr.need) {
              isSubmit = false;
              msg = '亲， 没有选择上传文件哦';
              break
            }
          }
        }
      }

      // 图片数据作为表单提交
      if (this.isForm.isImg[pageId_] || groupCompId) {
        let imgList = document.getElementById(submitContainerId).getElementsByClassName("wb-img");
        let imgUrl = null;
        let img = null,imgCompData = null,compId,tableName_,tableName;
        for(let index = 0, len = imgList.length; index < len; index++) {
          imgUrl = null;
          img = imgList[index];
          compId = img.dataset.id
          imgCompData = this.componentMap[compId];
          if(this.formValues[compId]) {
            imgUrl = this.formValues[compId].url
          };
          if(imgUrl && imgUrl.length > 0) {
            tableName_ = imgCompData.commonAttr.tableName ? imgCompData.commonAttr.tableName : '';
            tableName = 'img' + tableName_ + '_' + index;
            params[tableName] = imgUrl;
          }else {
            if(imgCompData.commonAttr.need) {
              isSubmit = false;
              msg = '亲， 图片尚未上传完成哦，请稍等！';
              break
            }
          }
        }
      }
      if (isSubmit) {
        if (_.keys(params).length <= 0) {
          msg = "没有填写必填项或是没有选则必选项！"
          EventBus.$emit("resetSubmitStatus")
          this.showToast(msg)
        }else{
          if(isCheckboxRelate){
            //发送 多选关联id 的事件 站点608
            let arr = item.events.submit.comps[1].attrs.value.split("$")
            if(arr.length > 1){
              let compId = arr[1]
              let selecteds = this.formValues[compId].selecteds
              let delayTime = 0
              _.forEach(selecteds, (selectedId) => {
                window.setTimeout( () => {
                  EventBus.$emit("itemClick", {id: compId, index: selectedId-1})
                }, delayTime)
                delayTime += 500
              })
              EventBus.$emit("resetSubmitStatus")
              EventBus.$emit("wbSubmitCallback", {e, compId})
            }
          }else{
            // 获取 controls
            let strCompId = item.id;
            const submitControlData = this.controls[item.id] && this.controls[item.id].submit;
            if(submitControlData) {
              let strRelateCompId = submitControlData.data && submitControlData.data.relateCompId ? submitControlData.data.relateCompId : '';
              let arrRelateCompId = strRelateCompId.split('$');
              strCompId = arrRelateCompId.length > 2 ? arrRelateCompId[1] : item.id;
            }
            // post
            let fr = getQueryString("stfr");
            let params_ = { data_str: JSON.stringify(params), fr: fr ? fr : "", type: EVENT_HOVER_TYPES.submit.type , com_id: strCompId, e, item}
            //提交按钮只能提交一次
            if (!this.siteInfo.formIsSubmit) {
              EventBus.$emit("wbSubmitCallback", {e, compId: item.id})
              this.showToast("提交数据是一样的, 不要重复提交哦！！")
              return
            }else{
              this.post("/Feact/formdata/", params_)
            }
          }
        }
      } else {
        EventBus.$emit("resetSubmitStatus")
        this.showToast(msg)
      }
    }
  },
  beforeUnmount(){
    EventBus.$off("wbsubmit")
    EventBus.$off("login")
    EventBus.$off("share")
    EventBus.$off("toast")
  },
};
</script>
